﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using LRSystem;
using System.Timers;
using System.Windows.Threading;
using System.Windows.Forms;
using System.Diagnostics;//记得加入此引用
using System.IO;
using ZKChartLibrary;
using System.Net;
using UDPServer;
namespace ModuleConfig
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 
    public partial class MainWindow : Window
    {
        public CurrentBaudRate CurrentBaudRate { get; set; }    // 当前波特率
        public CurrentPort CurrentPort { get; set; }            // 当前的串口号
        public List<Port> PortList { get; set; }                // 串口Port名列表
        static MagneticSerialPort sp;
        //private System.Timers.Timer aTimer;
        private delegate void Log(string txt, bool isEnable);
        public Numeric xMax { get; set; }
        //public Numeric xMin { get; set; }
        public Numeric yMax { get; set; }
        public Numeric yMin { get; set; }
        public CheckValue Line1CheckValue { get; set; }
        public CheckValue Line2CheckValue { get; set; }
        public CheckValue Line3CheckValue { get; set; }
        public CheckValue isStart { get; set; }
        System.Windows.Media.Brush[] Hbrsh = new Brush[3];
        private CheckValue[] chck = new CheckValue[3];

        private AsyncUDPServer udpserver;
        bool bUDPStart = false;

        //double leftmargin = 45;
        //double topbuttommargin = 15;
        //List<int>[] dotlist = new List<int>[3];
        //DateTime LastTime = default(DateTime);// 记录上次刷图时间
        public MainWindow()
        {
            CurrentBaudRate = new CurrentBaudRate();
            CurrentPort = new CurrentPort();
            // 动态生成串口Port名列表
            string[] ports = SerialPort.GetPortNames();         // 获取目前可用的Port.
            if(ports.Length!=0)
                CurrentPort.Port = ports[0];
            PortList = new List<Port>();
            foreach (string port in ports)
            {
                PortList.Add(new Port(port));
            }
            //
            yMax = new Numeric(-32768, 32767, 32767);
            yMin = new Numeric(-32768, 32767, -32768);
            xMax = new Numeric(50, 50000, 500);
            chck[0] =Line1CheckValue = new CheckValue(true);
            chck[1] = Line2CheckValue = new CheckValue(true);
            chck[2] = Line3CheckValue = new CheckValue(true);

            Hbrsh[0] = System.Windows.Media.Brushes.Red;
            Hbrsh[1] = System.Windows.Media.Brushes.Green;
            Hbrsh[2] = System.Windows.Media.Brushes.Blue;
            
            InitializeComponent();
            isStart = new CheckValue(false);
            ChartData d1 = new ChartData(new List<int>(), Hbrsh[0], Line1CheckValue.isChecked);
            ChartData d2 = new ChartData(new List<int>(), Hbrsh[1], Line1CheckValue.isChecked);
            ChartData d3 = new ChartData(new List<int>(), Hbrsh[2], Line1CheckValue.isChecked);
            zkLineChart.AddNewLine(d1);
            zkLineChart.AddNewLine(d2);
            zkLineChart.AddNewLine(d3);
            MagneticOriginalPacket.EvProcessReceivedPacket += MagneticOriginalPacket_EvProcessReceivedPacket;
            DataContext = this;                                 // 设定相应XMAL的上下文
        }

        private void OnOpenPort(object sender, RoutedEventArgs e)
        {
            try
            {
                sp = new MagneticSerialPort(CurrentPort.Port, CurrentBaudRate.Rate);
                sp.Open();   // Open the serial port;

                OpenPortBtn.IsEnabled = false;
                ClosePortBtn.IsEnabled = true;
            }
            catch (Exception ipexp)
            {
                System.Windows.MessageBox.Show(ipexp.Message);
            }
        }

        private void OnClosePort(object sender, RoutedEventArgs e)
        {
            if(sp!=null)
                sp.Close();                     // Close serial port.
            OpenPortBtn.IsEnabled = true;
            ClosePortBtn.IsEnabled = false;
        }
 
        private void OnClosed(object sender, EventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }

        void MagneticOriginalPacket_EvProcessReceivedPacket(baseReceivedPacket pk)
        {
            //if (isStart.isChecked)
            //{
            int n1 = (pk as MagneticReport).numb1;
            int n2 = (pk as MagneticReport).numb2;
            int n3 = (pk as MagneticReport).numb3;
            zkLineChart.AddData(0, n1);
            zkLineChart.AddData(1, n2);
            zkLineChart.AddData(2, n3);
            //}

        }

        private void OnStartClicked(object sender, RoutedEventArgs e)
        {
            if (isStart.isChecked)
            {
                isStart.isChecked = false;
                bStartBtn.Content = "启动";
                
                //MagneticOriginalPacket.EvProcessReceivedPacket -= MagneticOriginalPacket_EvProcessReceivedPacket;
            }
            else{
                isStart.isChecked = true;
                bStartBtn.Content = "停止";
                zkLineChart.ClearAll();
                //zkLineChart.Start = true;
                //MagneticOriginalPacket.EvProcessReceivedPacket += MagneticOriginalPacket_EvProcessReceivedPacket;
            }
        }

        private void OnClickBrowsFile(object sender, RoutedEventArgs e)
        {
            try
            {
                SaveFileDialog save = new SaveFileDialog();       // 定义打开文本框实体
                save.Title = "Save file";                         // 对话框标题
                save.Filter = "File（.txt）|*.txt|All files|*.*"; // 文件扩展名
                save.FileName = "Data" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
                if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Write(save.FileName);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        public void Write(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            //for(int i=0; i<dotlist[0].Count; i++)
            //    sw.Write(dotlist[0][i] + "," + dotlist[1][i] + "," + dotlist[2][i] + "\n");
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }

        private void OnLine1Checked(object sender, RoutedEventArgs e)
        {
            zkLineChart.SetIsDraw(0, Line1CheckValue.isChecked);
        }

        private void OnLine1UnChecked(object sender, RoutedEventArgs e)
        {
            zkLineChart.SetIsDraw(0, Line1CheckValue.isChecked);
        }

        private void OnLine2Checked(object sender, RoutedEventArgs e)
        {
            zkLineChart.SetIsDraw(1, Line2CheckValue.isChecked);
        }

        private void OnLine2UnChecked(object sender, RoutedEventArgs e)
        {
            zkLineChart.SetIsDraw(1, Line2CheckValue.isChecked);
        }

        private void OnLine3Checked(object sender, RoutedEventArgs e)
        {
            zkLineChart.SetIsDraw(2, Line3CheckValue.isChecked);
        }

        private void OnLine3UnChecked(object sender, RoutedEventArgs e)
        {
            zkLineChart.SetIsDraw(2, Line3CheckValue.isChecked);
        }

        private void OnOpenUDP(object sender, RoutedEventArgs e)
        {
            if (bUDPStart == false)
            {
                int port = UInt16.Parse(localPortCtrl.Text);
                udpserver = new AsyncUDPServer(IPAddress.Any, UInt16.Parse(localPortCtrl.Text));
                udpserver.DataReceived += Udpserver_DataReceived;
                udpserver.Start();
                if (udpserver.IsRunning)
                {
                    OpenUDPBtn.Content = "停止";
                    bUDPStart = true;
                }
                else
                {
                    System.Windows.MessageBox.Show($"无法打开端口{port}");
                }
            }
            else
            {
                udpserver.Stop();
                OpenUDPBtn.Content = "开始";
                bUDPStart = false;
            }

        }

        private void Udpserver_DataReceived(object sender, AsyncUDPEventArgs e)
        {
            List<byte> rxPacket = new List<byte>();
            
            for (int i = 0; i < e.msgData.Length; i++)
            {
                rxPacket.Add(e.msgData[i]);                                    // 将收到的所有数据存入list.
            }
            MagneticOriginalPacket.PacketParse(sender, rxPacket);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Title += System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
    }
}
